1843D - Apple Tree - CodeForces Solution


combinatorics dfs and similar dp trees

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void dfs(ll node, vector<int> adj[], vector<bool> &vis, vector<ll> &leaf)
{
  vis[node] = true;
  if (adj[node].size() == 1 && node != 1)
    leaf[node] = 1;

  for (auto &nei : adj[node])
  {
    if (!vis[nei])
    {
      dfs(nei, adj, vis, leaf);
      leaf[node] += leaf[nei];
    }
  }
}

int main()
{
  int t;
  cin >> t;
  while (t--)
  {
    int n;
    cin >> n;
    vector<int> adj[n + 1];
    for (int i = 0; i < n - 1; i++)
    {
      int a, b;
      cin >> a >> b;
      adj[a].push_back(b);
      adj[b].push_back(a);
    }
    vector<bool> vis(n + 1, false);
    vector<ll> leaf(n + 1, 0);

    dfs(1, adj, vis, leaf);

    int q;
    cin >> q;
    for (int i = 0; i < q; i++)
    {
      int x, y;
      cin >> x >> y;
      cout << leaf[x] * leaf[y] * 1LL << endl;
    }
  }
  return 0;
}


Comments

Submit
0 Comments
More Questions

988B - Substrings Sort
312A - Whose sentence is it
513A - Game
1711E - XOR Triangle
688A - Opponents
20C - Dijkstra
1627D - Not Adding
893B - Beautiful Divisors
864B - Polycarp and Letters
1088A - Ehab and another construction problem
1177B - Digits Sequence (Hard Edition)
1155B - Game with Telephone Numbers
1284A - New Year and Naming
863B - Kayaking
1395B - Boboniu Plays Chess
1475D - Cleaning the Phone
617B - Chocolate
1051B - Relatively Prime Pairs
95B - Lucky Numbers
1692D - The Clock
1553D - Backspace
1670D - Very Suspicious
1141B - Maximal Continuous Rest
1341A - Nastya and Rice
1133A - Middle of the Contest
385A - Bear and Raspberry
1311B - WeirdSort
1713F - Lost Array
236B - Easy Number Challenge
275A - Lights Out